<?php


class Comments extends A_Content {
	
	public function add() {
		$this->_top->_sql->exeDummy("INSERT INTO ".TAB_PREF."comments(add_date) VALUES(NOW());");
		$id = $this->_top->_sql->last_insert_id();
		return $this->getById($id);
	}
	
	
	public function getById($id) {
		if (!isset($this->_cashe_obj[$id])) {
                $this->_cashe_obj[$id] = new Comment($this->_top,$this,$id);
		}
		return $this->_cashe_obj[$id];
	}
	
	public function CommentSearch()
	{
		return new CommentSearch($this->_top,$this);
	}
}



class Comment extends A_SingleContent {
    protected 
        $_cashe_obj = array(); //кэш для отдельных комментариев

    protected $_comments; //список идешников комментариев        
        
	protected function loader() {
		$get_data = $this->_top->_sql->exe("SELECT * FROM ".TAB_PREF."comments WHERE comments_id={$this->_content_id}");
		if (count($get_data)==0) { //создаем ветку комментариев
			throw $this->_top->Utils->PushError('Comments object not found Id: '.$this->_content_id,'Системная ошибка. Обратитесь к администратору');
		} else {
			$this->_data = $get_data;
		}
		
		//загружаем идешники комментариев
		$this->_comments = $this->_top->_sql->exe("SELECT id FROM ".TAB_PREF."comments_list WHERE comment_id={$this->_content_id}");
	}
	
	public function __get($param) {
	   if( $param == 'nonCheckedCount' ){//нужно кол-во непроверенных комментов
	       $get = $this->_top->_sql->exe("SELECT * FROM ".TAB_PREF."comments_list WHERE comment_id={$this->_content_id} and checked_f=0");
	       return count($get);
	   }
	}
	
	public function __set($param, $value) {
	
	}
	
	protected function deleter() {
	
	}

	public function length(){ //кол-во отзывов
        $get_count = $this->_top->_sql->exe("SELECT count(*) as c ".
            "FROM ".TAB_PREF."comments_list WHERE comment_id=$this->_content_id");
        return $get_count[0]['c'];	
	}	

	//вставляем комментарий
	public function add($aUser_id, $aMessage){	   
        echo "INSERT INTO ".TAB_PREF."comments_list(comment_id, message, user_id, add_date, checked_f) ".
            "values($this->_content_id, '$aMessage', $aUser_id, NOW(), false)";
        $this->_top->_sql->exeDummy("INSERT INTO ".TAB_PREF."comments_list(comment_id, message, user_id, add_date, checked_f) ".
            "values($this->_content_id, '$aMessage', $aUser_id, NOW(), false)");
//        return $this->getById($this->_top->_sql->last_insert_id());
	}

	public function getById($aId){
	   if (!isset($this->_cashe_obj[$aId])) {
			$this->_cashe_obj[$aId] = new SingleComment($this->_top, $this, $aId);
		}
		
		return $this->_cashe_obj[$aId];		
	}

	public function item($aIndex){
	   $id = $this->_comments[$aIndex]['id'];
	   if (!isset($this->_cashe_obj[$id])) {
			$this->_cashe_obj[$id] = new SingleComment($this->_top, $this, $id);
		}
		
		return $this->_cashe_obj[$id];		
	}
	
	/**
	 * возвращает true, если пользоватеь уже в эту ветку писал
	 *
	 * @param unknown_type $aUserId
	 */
	public function isWriten($aUserId){
        $get = $this->_top->_sql->exe("SELECT comment_id ".
            "FROM ".TAB_PREF."comments_list WHERE comment_id=$this->_content_id AND user_id=$aUserId");
        if( count($get) ) //да, есть уже коммент от этого пользователя
            return true;
        return false;
	}
}


class CommentSearch
{
    protected 
        $_cashe_obj = array(); //кэш для отдельных комментариев
        
	private $_limits = null, $_total_amount=null;
	private 
		$_top, $_comment_list, $search_params = array(), $found = false;
	
	function __construct($top, $comment_list)
	{
		$this->_top = $top;
		$this->_comment_list = $comment_list;
	}
	
	public function setLimits($from_row,$amount) {
		$this->_limits = array($from_row,$amount);
		return $this;
	}	
	
	public function __set($param,$value)
	{
        $value = $this->_top->Utils->prepareValueForSQL($value);
		if( $value != "" ){
            $value = str_replace('*', '%', $value);
            array_push($this->search_params," AND $param = '$value'");
		}
	}	
	
	public function Make()
	{
        //определим общее кол-во записей
//        echo "SELECT count(*) as c FROM ".TAB_PREF."user_list WHERE 1 ".implode(" ",$this->search_params);
		$get_amount = $this->_top->_sql->exe("SELECT count(*) as c FROM ".TAB_PREF."comments_list WHERE 1 ".implode(" ",$this->search_params).' order by add_date');
		$this->_total_amount = $get_amount[0]['c'];

		$this->found = array();
		
//		echo "SELECT comment_id, user_id FROM ".TAB_PREF."comments_list WHERE 1 ".implode(" ",$this->search_params).
//		  ($this->_limits!==null ? " LIMIT {$this->_limits[0]},{$this->_limits[1]}" : '');
		$comments = $this->_top->_sql->exe("SELECT id FROM ".TAB_PREF."comments_list WHERE 1 ".implode(" ",$this->search_params).
		  ($this->_limits!==null ? " LIMIT {$this->_limits[0]},{$this->_limits[1]}" : '')		
		);

        for ($u=0;$u<count($comments);$u++)
			array_push($this->found, $comments[$u]['id'] );

		return true;
	}	
		
	public function total_length() {
		return $this->_total_amount;
	}	
		
	public function length()
	{
		if (!$this->found) return false;
		return count($this->found);
	}

	public function item($aIndex)
	{
		if (!$this->found)
            return false;
	   
//        Zend_Debug::dump($this->found);
       $id = $this->found[$aIndex];
	   if (!isset($this->_cashe_obj[$id])) {
			$this->_cashe_obj[$id] = new SingleComment($this->_top, $this, $id);
		}
	
		return $this->_cashe_obj[$id];	
	}	
	
}



/**
 * Класс-абстракция одного комментария
 *
 */
class SingleComment extends A_SingleContent {
        
//		$this->_top - это ссылка на экземпляр списка заказов
//		$this->_parent =& $parent - ссылка на экземпляр заказа, в котором находится данный товар
//		$this->_content_id = $id - это идентификатор товара
		
    protected function loader(){
		$item_data = $this->_top->_sql->exe("SELECT * FROM ".TAB_PREF."comments_list ".
            "WHERE id=$this->_content_id");        
		if (count($item_data)==0) {
			throw $this->_top->Utils->PushError("COMMENT '$this->_content_id' NOT FOUND", "Комментарий не найден");
		} else {
			$this->_data = $item_data[0];
			
        //подтянем фио пользователя
        $users = MF_Main::getInstance()->UserList;
		$user = $users->UserSearch();
		$user->user_id = $this->_data['user_id'];
		$user->Make();
		
		$this->_data['user'] = $user->item(0);;
		
		//загружаем товары с привязкой к справочнику
//			$goods = $this->_top->_sql->exe("SELECT a.*, b.* FROM ".TAB_PREF."order_good a, ".TAB_PREF."catalog_item b WHERE a.item_id = b.item_id and order_id=$this->_content_id");
//			for ($i=0; $i < count($goods); $i++)
//                array_push($this->_goods, $goods[$i]);
//			$profile_class = $this->_top->OrderList->_profile_class_name;
//			$this->_profile_class = new $profile_class($this->_top,$this,$this->_content_id);
		}
		
//		Zend_Debug::dump($this->_data);
	}

	public function __get($param)
	{
//		} elseif (!isset($this->_data[$param])) { 
//			return $this->_profile_class->$param;
//		} else {
		return $this->_data[$param];
//		}
	}

	public function __set($param,$value)
	{
//		if (!isset($this->_data[$param])) {
//			$this->_profile_class->$param = $value;
//		}else{
			$value = $this->_top->Utils->prepareValueForSQL($value);
				
			$this->_top->_sql->exeDummy("UPDATE ".TAB_PREF."comments_list SET $param='$value' ".
                "WHERE id=$this->_content_id ");
			$this->_data[$param] = $value;
			return true;
//		}
	}

	public function deleter()
	{	   
		$this->_top->_sql->exeDummy("DELETE FROM ".TAB_PREF."comments_list WHERE id={$this->_content_id}");
	}		
}


?>